<?php

namespace app\common\service;

use app\bbs\model\MessageUser;
use app\http\exception\ApiException;
use randy\tools\units\ExtendQueryHelper;

class MessageUserService extends BaseService
{
    public function getMessageUserList(ExtendQueryHelper $extendQueryHelper, $data)
    {
        $query = MessageUser::build()
                            ->withJoin(['message'])
                            ->where($extendQueryHelper->where)
                            ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        $list = $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
        return $list;
    }

    public function getMessageUserItem($id)
    {
        return MessageUser::build()
                          ->findOrFail($id);
    }

    public function delMessageUserItem($id)
    {
        $info = MessageUser::find($id);
        return $info->delete();
    }

    public function setMessageUserItem($id, $data)
    {
        $info = MessageUser::find($id);
        $info->save($data);
        return $info;
    }


    public function addMessageUserItem($data)
    {
        $model = new MessageUser();
        $model->save($data);
        return $model;
    }

    public function getTotal($user_id, $type)
    {
        $total = MessageUser::build()
                            ->withJoin(['message'])
                            ->where('message_user.user_id', $user_id)
                            ->whereIn('message.type', $type)
                            ->where('message_user.is_read', 0)
                            ->count();
        return $total;
    }

    public function setIsRead($message_user_id)
    {
        $message = MessageUser::build()
                              ->find($message_user_id);
        $message->is_read = 1;
        $message->save();
        return true;
    }

    public function setAllIsRead($user_id, $type)
    {
        $message = MessageUser::build()
                              ->join('message', 'message.message_id =message_user.message_id')
                              ->where('message.type', 'IN', $type)
                              ->where('user_id', $user_id)
                              ->save(['is_read' => 1]);
        return true;
    }


}
